import os
import re
import sqlite3

from Function import Database, FileOperation, Data
import Function.People as People
from Data import GlobalValue


def menu_display(menu_list: list) -> int:
    """
    显示菜单，并返回选择的值
    输入：菜单名称列表
    输出：打印整个菜单
    返回：选择的数字
    """
    while True:
        num = 0
        for item in menu_list:
            num += 1
            print(f"{num}.{item}")
        print("0.退出")

        try:
            choice_str = input("请输入序号：")
            choice_num = int(choice_str)
        except KeyboardInterrupt:
            os.system("cls")
            print("程序结束\n")
            return 0
        except ValueError:
            print("输入数字不为整数，请重新输入")
        else:
            return choice_num


def delete_folder_path():
    # 读取数据库数据
    folder_list = Database.read_data_to_list(GlobalValue.database_address, "folder_list")
    for item in folder_list:
        print(f"ID:{item[0]}，路径：{item[1]}")
    folder_path_id = input("请输入要删除的文件路径序号：")
    Database.delete_data_by_ID(GlobalValue.database_address, "folder_list", int(folder_path_id))
    print("删除成功")
    input("按Enter键继续……")


def add_folder_path():
    folder_path = input("请输入文件夹路径：")
    conn = sqlite3.connect(GlobalValue.database_address)
    cursor = conn.cursor()
    sql = 'insert into folder_list (folder_path) values (?)'
    cursor.execute(sql, (folder_path,))
    conn.commit()
    cursor.close()
    conn.close()
    print("添加完成\n")
    input("按Enter键继续……")


def statistics_display():
    # 读取数据库，获取文件夹路径列表
    folder_list = Database.read_data_to_list(GlobalValue.database_address, "folder_list")
    # 获取班级学生的信息列表(姓名，学号）
    students_info_list = Database.read_data_to_list(GlobalValue.database_address, "professional_students")
    # 获取班级学生的学号
    student_id_number_list = Database.read_column_data_to_list(GlobalValue.database_address, "professional_students", "ID")
    # 获取班级学生的姓名
    student_name_list = Database.read_column_data_to_list(GlobalValue.database_address, "professional_students", "name")
    # 获取专业学生的信息列表(姓名，学号）
    professional_students_info_list = Database.read_data_to_list(GlobalValue.database_address, "professional_students")

    # 判断文件夹列表是否为空
    if len(folder_list) == 0:
        # 文件夹列表为空，就直接结束
        print("输出完毕，列表为空\n")
    else:
        # 遍历文件夹列表
        for folder in folder_list:
            # 获取文件夹中所有文件的名称
            try:
                file_name = FileOperation.get_file_and_folder_full_name_from_folder(folder[1])
            except FileNotFoundError:
                print(f"未发现文件夹：{folder[1]}")
                print("建议删除此文件夹路径\n")
                break

            # 文件名称根据正则表达式匹配
            num_id_list = []
            for item in file_name:
                # 匹配规则：20xx21xxxx
                result = re.search(r'20\d{2}21\d{4}', item)
                try:
                    # 匹配到内容
                    num_id_list.append(result.group())
                except AttributeError:
                    # 没有匹配到内容，不处理
                    pass

            # 判断id列表是否为空
            if len(num_id_list) == 0:
                # id列表为空，说明文件名称没有学号，就以姓名统计

                # 提交的学生名字列表
                commit_students_name_list = []
                # 未提交的学生名字列表，默认所有学生均未提交
                uncommit_students_name_list = student_name_list

                for item in file_name:
                    # 使用正则表达式来匹配中文名字，假设名字由2到3个汉字组成
                    result = re.search(r'\b[\u4e00-\u9fa5]{2,3}\b', item)
                    try:
                        commit_students_name_list.append(result.group())
                    except AttributeError:
                        # 没有匹配到内容，不处理
                        pass
                # 显示统计的文件夹
                print(f"文件夹ID：{folder[0]}\n文件夹路径：{folder[1]}\n")
                # 输出结果
                print(f"已经提交（{len(commit_students_name_list)}）人：", end=" ")
                for name in commit_students_name_list:
                    print(name, end=" ")
                    # 在未提交学生姓名列表中去除已经提交的学生，剩下的就是未提交的学生
                    if name in uncommit_students_name_list:
                        uncommit_students_name_list.remove(name)
                print("")
                print(f"未提交（{len(uncommit_students_name_list)}）人：", end=" ")
                for name in uncommit_students_name_list:
                    print(name, end=" ")
                print("\n")

            else:
                # id列表不为空，说明文件名称以学号统计
                # 计数
                count_result_dict = Data.list_count(student_id_number_list, num_id_list)

                # 统计非本班学生
                not_class_students_id = []
                not_class_students_name = []
                for id_num in num_id_list:
                    if id_num not in student_id_number_list:
                        not_class_students_id.append(id_num)
                for id_num in not_class_students_id:
                    for info in professional_students_info_list:
                        if id_num in info:
                            not_class_students_name.append(info[0])

                # 获取计数结果
                all_students_dic = People.getAllStudentsDic(count_result_dict, student_id_number_list)
                undo_id_list = all_students_dic.get('undo')
                done_id_list = all_students_dic.get('done')

                # 将id转换为对应的name
                undo_name_list = []
                done_name_list = []
                for item in undo_id_list:
                    for info in students_info_list:
                        if item in info:
                            undo_name_list.append(info[0])
                for item in done_id_list:
                    for info in students_info_list:
                        if item in info:
                            done_name_list.append(info[0])

                # 显示统计的文件夹
                print(f"文件夹ID：{folder[0]}\n文件夹路径：{folder[1]}\n")
                # 输出ID
                print(f"未完成（{len(undo_id_list)}人）：{' '.join(undo_id_list)}")
                print(f"已完成（{len(done_id_list)}人）：{' '.join(done_id_list)}")
                print(f"其他班提交（{len(not_class_students_id)}人）：{' '.join(not_class_students_id)}")
                print("")
                # 输出姓名
                print(f"未完成（{len(undo_name_list)}人）：{' '.join(undo_name_list)}")
                print(f"已完成（{len(done_name_list)}人）：{' '.join(done_name_list)}")
                print(f"其他班提交（{len(not_class_students_name)}人）：{' '.join(not_class_students_name)}")
                print("\n\n")


def menu():
    menu_list = ["添加文件夹路径", "删除文件夹路径", "刷新显示"]

    while True:
        os.system('cls')
        statistics_display()
        choose = menu_display(menu_list)
        os.system('cls')
        match choose:
            case 1: add_folder_path()
            case 2: delete_folder_path()
            case 3: continue
            case 0: break
